package io.qifan.desktop.client.socket;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CompleteResult<T> implements AsyncResult<T> {
    static final int RUNNING = 1;
    static final int FAILED = 2;
    static final int COMPLETED = 3;
    volatile int state = RUNNING;
    private final CountDownLatch countDownLatch = new CountDownLatch(1);
    T result;

    @Override
    public T getResult() throws TimeoutException, InterruptedException {
        boolean await;
        try {
            await = countDownLatch.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            this.state = FAILED;
            throw e;
        }
        if (await && state != COMPLETED) {
            this.state = FAILED;
            throw new TimeoutException();
        }
        return result;
    }

    @Override
    public boolean isComplete() {
        return state == COMPLETED;
    }

    @Override
    public void complete(T t) {
        result = t;
        countDownLatch.countDown();
    }
}
